package common.util;

import common.entity.JgTreeEntity;

import java.util.ArrayList;
import java.util.List;


/**
 * 递归构造树型结构
 */
public class JgTreeUtil {

    private List<JgTreeEntity> jgList = new ArrayList<>();

    /**
     * 建立树形结构
     * @param jgList  机构集合
     * @param jgbm  根机构编码
     * @return
     */
    public List<JgTreeEntity> builTree(List<JgTreeEntity> jgList, String jgbm) {
        this.jgList = jgList;
        List<JgTreeEntity> treeResults = new ArrayList<>();
        for (JgTreeEntity JgTreeNode : getRootNode(jgbm)) {
            JgTreeNode = buildChilTree(JgTreeNode);
            treeResults.add(JgTreeNode);
        }
        return treeResults;
    }

    /**
     * 递归，建立子树形结构
     * @param pNode 上级机构实体
     * @return
     */
    private JgTreeEntity buildChilTree(JgTreeEntity pNode) {
        List<JgTreeEntity> chilJgTrees = new ArrayList<>();
        for (JgTreeEntity jgTreeNode : jgList) {
            if (jgTreeNode.getSjjgbm().equals(pNode.getJgbm())) {
                chilJgTrees.add(buildChilTree(jgTreeNode));
            }
        }
        pNode.setChildren(chilJgTrees);
        return pNode;
    }

    /**
     * 获取根节点
     * @param jgbm
     * @return
     */
    private List<JgTreeEntity> getRootNode(String jgbm) {
        List<JgTreeEntity> rootJgTrees = new ArrayList<>();
        for (JgTreeEntity jgTreeNode : jgList) {
            if (jgTreeNode.getSjjgbm().equals(jgbm)) {
                rootJgTrees.add(jgTreeNode);
            }
        }
        return rootJgTrees;
    }

}









